<template>
  <d2-container>
  <!--峰谷电分析-->
  <section class="app-container">
    <el-row :span="24">

      <el-col :span="18" >
        <el-col :span="24">
          <div class="search-area">
            <el-form label-position="right" :model="dataForm" :inline="true">
              <el-form-item label="日期" label-width="40px">
                <el-date-picker
                  v-model="dataForm.date"
                  placeholder="时间范围"
                  style="width: 150px;"
                  class="filter-item"
                  size="mini"
                  :picker-options="pickerOptions1"
                  :type="dataForm.dateType"
                  suffix-icon="el-icon-date"
                  clearable
                  @keyup.enter.native="getDataList"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-radio-group v-model="dataForm.dateTypeDesc" size="mini" @change="getDataList">
                  <el-radio-button :label="item.typeDesc" v-for="(item, index) in Config.searchDate" :key="index">
                    {{item.label}}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
              <div style="display:inline-block; float:right;">
                  <el-form-item>
                    <el-button
                      class="filter-item"
                      type="primary"
                      icon="el-icon-search"
                      size="mini"
                      @click="getDataList"
                    >查询</el-button>
                    <el-button
                      class="filter-item"
                      style="margin-left: 10px"
                      type="primary"
                      icon="el-icon-download"
                      size="mini"
                      @click="exoprtData"
                    >导出</el-button>
                  </el-form-item>
              </div>
            </el-form>
          </div>
        </el-col>
        <el-col :span="24">
          <el-col :span="24" v-show="dataForm.dateTypeDesc=='1'">
            <!--  day  report -->

            <el-col :span="24" style="width: 100%;overflow:auto;" >
              <el-table :data="dayDataList" border style="width: 100%;overflow:visible;"  v-loading="dataListLoading1">
                <el-table-column
                  prop="ObjName"
                  header-align="center"
                  align="center"
                  label="区域"
                ></el-table-column>
                <el-table-column
                  prop="meterName"
                  header-align="center"
                  align="center" min-width="120"
                  label="计量器具名称"
                ></el-table-column>
                <el-table-column
                  prop="time"
                  header-align="center"
                  align="center"
                  label="小时"
                ></el-table-column>
                <el-table-column
                  prop="type"
                  header-align="center"
                  align="center"
                  label="类型"
                ></el-table-column>
                <el-table-column
                  prop="val"
                  header-align="center"
                  align="center"
                  :label="`用量(kWh)`"
                >
                </el-table-column>
                <el-table-column
                  prop="fee"
                  header-align="center"
                  align="center"
                  label="金额(元)"
                ></el-table-column>

              </el-table>
            </el-col>

          </el-col>
          <el-col :span="24" v-show="dataForm.dateTypeDesc=='2'">
            <el-col :span="24" style="width: 100%;overflow:auto;" >
              <el-table :data="monthDataList" border style="width: 100%;overflow:visible;" v-loading="dataListLoading1">
                <el-table-column
                  prop="buildingName"
                  header-align="center"
                  align="center"
                  label="区域"
                >
                </el-table-column>
                <el-table-column
                  prop="meterCode"
                  header-align="center"
                  align="center" min-width="120"
                  label="计量器具名称"
                >
                </el-table-column>
                <el-table-column
                  prop="time"
                  header-align="center"
                  align="center"
                  label="日期"
                ></el-table-column>

                <el-table-column :label="item.name" v-for="(item, index) in monthheader" :key="index"  align="center" >
                  <template slot-scope="scope">
                    <span v-for="(item2,index2) in scope.row.value" v-if="item.indexName == item2.priceName"> {{ scope.row.value[index2][item.key] }} </span>
                  </template>
                </el-table-column>


                <el-table-column
                  prop="totalVal"
                  header-align="center"
                  align="center"
                  :label="`总用量(kWh)`"
                >
                </el-table-column>
                <el-table-column
                  prop="totalFee"
                  header-align="center"
                  align="center"
                  label="总金额(元)"
                ></el-table-column>

              </el-table>
            </el-col>

          </el-col>
          <el-col :span="24" v-show="dataForm.dateTypeDesc=='3'">
            <el-col :span="24" style="width: 100%;overflow:auto;" >
              <el-table :data="yearDataList" border style="width: 100%;overflow:visible;" v-loading="dataListLoading1">
                <el-table-column
                  prop="buildingName"
                  header-align="center"
                  align="center"
                  label="区域"
                >
                </el-table-column>
                <el-table-column
                  prop="meterCode"
                  header-align="center"
                  align="center" min-width="120"
                  label="计量器具名称"
                >
                </el-table-column>
                <el-table-column
                  prop="time"
                  header-align="center"
                  align="center"
                  label="月份"
                ></el-table-column>

                <el-table-column :label="item.name" v-for="(item, index) in yearheader" :key="index"  align="center" >
                  <template slot-scope="scope">
                    <span v-for="(item2,index2) in scope.row.value" v-if="item.indexName == item2.priceName"> {{ scope.row.value[index2][item.key] }} </span>
                  </template>
                </el-table-column>


                <el-table-column
                  prop="totalVal"
                  header-align="center"
                  align="center"
                  :label="`总用量(kWh)`"
                >
                </el-table-column>
                <el-table-column
                  prop="totalFee"
                  header-align="center"
                  align="center"
                  label="总金额(元)"
                ></el-table-column>

              </el-table>
            </el-col>

          </el-col>
        </el-col>
      </el-col>
      <el-col :span="6" class="device-area1">

        <el-aside >
          <el-row class="search-area">
            <el-input size="mini" style="width:95%" v-model="searchKey" placeholder="姓名或电话" clearable></el-input>
          </el-row>
          <el-table ref="rentTable" :show-header="false" highlight-current-row current-row-key="subscriberId" empty-text="无租户信息" @row-click="selectRent" :data="rentList"  v-loading="dataListLoading"  style="width: 99%;">
            <el-table-column min-width="100"  prop="subscriberName" header-align="center" align="center"></el-table-column>
            <el-table-column min-width="150" prop="phone" header-align="center" align="center"></el-table-column>
          </el-table>
          <!--鼠标右键点击出现菜单-->
        </el-aside>



        <!--<el-tree-->
          <!--:style="'height:'+(containerHeight-10)+'px'"-->
          <!--ref="buildTree"-->
          <!--highlight-current-->
          <!--node-key="id"-->
          <!--:data="buildDataList"-->
          <!--:expand-on-click-node="false"-->
          <!--:props="menuListTreeProps"-->
          <!--@node-click="selectBuild"-->
          <!--default-expand-all-->
        <!--&gt;-->
          <!--<span class="custom-tree-node"  slot-scope="{ node, data }">-->
            <!--<span :dataType="data.type">-->
                <!--<i class="el-icon-setting" style="padding: 6px;margin-left:-24px;" v-if="data.type=='b'&&node.isLeaf"></i>-->
                <!--<i class="el-icon-star-off" style="padding: 6px; margin-left:-24px;" v-if="data.type=='d'"></i>-->
                <!--<span style="margin-left:0px;"> {{ node.label }}</span>-->
            <!--</span>-->
          <!--</span>-->
        <!--</el-tree>-->
      </el-col>
    </el-row>
  </section>
  </d2-container>
</template>

<script>
  import * as echarts from "echarts"
  import Config from "@/utils/config"
  import commondef from '@/utils/common'
  import * as Util from "@/utils";
  export default {
    data () {
      return {
        dataListLoading: false,
        dataListLoading1: false,
        currentRentInfo:{},
        rentList:[],
        searchKey:'',
        rentOriginList:[],
        header:[],
        dayDataList:[],
        monthDataList:[],
        yearDataList:[],
        monthheader:[],
        yearheader:[],
        dataForm: {
          date:new Date(),
          dateType:'date',
          dateTypeDesc:'1'
        },
        menuListTreeProps: {
          label: "name",
          children: "children"
        },
        buildDataList:[],
        oralebuildDataList:[],
        currentBuildNode:{},
        Config:Config,
        activeName: '1',
        pickerOptions1: {
          disabledDate (time) {
            return time.getTime() > (new Date().getTime())
          }
        },
        query: {
          key: '',
          page_no: 1,
          page_size: commondef.globlePagesize,
          text: '',
          total: 0,
          list: []
        },
        option: {
          backgroundColor: '#FFFFFF',
          title: {
            show: false,
            text: '总用电量',
            x: 'right',
            top: 80,
            textStyle: {
              fontSize: '12'
            }
          },
          color: ['#D6E0FF', '#FE8252', '#F7BF31', '#678AF4'],
          tooltip: {
            trigger: 'item',
            formatter: '{b} ({d}%)'
          },
          grid: {
            x:50,
            y:25,
            x2:55,
            y2:25,
          },
          legend: {
            orient: 'vertical',
            align: 'left',
            x: 'right',
            itemWidth: 10,
            itemHeight: 10,
            y: 'center',
            itemGap: 20,
            data: [],
          },
          series: [
            {
              name: '日电量',
              type: 'pie',
              radius: [40, 80],
              center: ['35%', '50%'],
              roseType: 'radius',
              avoidLabelOverlap: false,
              label: {
                normal: {
                  show: true,
                  position: 'center',
                  formatter: '{a}',
                  textStyle: {
                    fontSize: '18',
                    color: '#333333'
                  }
                },
                emphasis: {
                  show: false,
                  textStyle: {
                    fontSize: '30',
                    fontWeight: 'bold'
                  }
                }
              },
              labelLine: {
                normal: {
                  show: false
                }
              },
              itemStyle: {
                normal: {
                  borderWidth: 3, //设置border的宽度有多大
                  borderColor: '#FFFFFF'
                }
              },
              data: []
            }
          ]
        },
        optiondf: {
          backgroundColor: '#FFFFFF',
          title: {
            text: '总用电费用',
            show: false,
            right: -5,
            top: 80,
            borderColor: '#D6E0FF',
            textStyle: {
              fontSize: '12'
            },
            barBorderRadius: 50,
            shadowBlur: 50,
            shadowOffsetX: 10,
            shadowColor: '#D6E0FF'
          },
          color: ['#D6E0FF', '#FE8252', '#F7BF31', '#678AF4','#2bd597','708ce5'],
          tooltip: {
            trigger: 'item',
            formatter: '{b} ({d}%)'
          },
          grid: {
            x:50,
            y:25,
            x2:55,
            y2:25,
          },
          legend: {
            orient: 'vertical',
            align: 'left',
            right: 30,
            y: 'center',
            itemGap: 20,
            itemWidth: 10,
            itemHeight: 10,
            data: []
          },
          series: [
            {
              name: '日电费',
              type: 'pie',
              radius: [40, 80],
              center: ['25%', '50%'],
              roseType: 'radius',
              avoidLabelOverlap: false,
              stillShowZero: true,
              label: {
                normal: {
                  show: true,
                  position: 'center',
                  formatter: '{a}',
                  textStyle: {
                    fontSize: '18',
                    color: '#333333'
                  }
                },
                emphasis: {
                  show: false,
                  textStyle: {
                    fontSize: '30',
                    fontWeight: 'bold'
                  }
                }
              },
              labelLine: {
                normal: {
                  show: false
                }
              },
              itemStyle: {
                normal: {
                  borderWidth: 3, //设置border的宽度有多大
                  borderColor: '#FFFFFF'
                }
              },
              data: []
            }
          ]
        },
        powerEchart: {
          option: {
            title: {
              text: '总用电费用',
              show: true,
              top: 5,
              borderColor: '#D6E0FF',
              textStyle: {
                fontSize: '14'
              }
            },
            grid: {
              left: 40,
              top: 60,
              right: 40,
              bottom: 40
            },
            yAxis: {
                type: 'value',
                scale: true,
                name: '单位：kWh',
                splitNumber: 6,
                min:0,
                boundaryGap: [0.2, 0.2],
                axisLabel: {
                  formatter: function (a) {
                    return a >= 1000
                      ? echarts.format.addCommas(a / 1000) + 'k'
                      : a
                  }
                }
            },
            color: ['#FE8252', '#F7BF31', '#678AF4','#2bd597','708ce5']
          },
          dateOption: {
            legend: {
              top: 10,
              right: 35,
              itemGap: 38,
              itemWidth: 10,
              itemHeight: 10,
              data: []
            },
            xAxis: {
              type: 'category',
              axisTick: {show: false},
              data: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23']
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              },
              formatter: function (val, n) {
                var returnStr = '<div style=\'text-align:left;\'>' +
                  '时间：' + val[0].name + ':00<br/>'
                for (var i in val) {
                  if (parseInt(val[i].value) > 0) {
                    returnStr = returnStr +
                      '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + val[i].color + '\'></span>' +
                      val[i].seriesName + '：' + val[i].value.toFixed(1) + ' kWh' +
                      '<br/>'
                  }
                }
                returnStr = returnStr + '</div>'
                return returnStr
              }
            }
          },
          monthOption: {
            legend: {
              top: 10,
              right: 35,
              itemGap: 38,
              itemWidth: 10,
              itemHeight: 10,
              data: []
            },
            xAxis: {
              type: 'category',
              data: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31']
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              },
              formatter: function (val, n) {
                var totle = 0
                var returnStr = '<div style=\'text-align:left;\'>' +
                  '时间：' + val[0].name + '<br/>'
                for (var i in val) {
                  returnStr = returnStr +
                    '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + val[i].color + '\'></span>' +
                    val[i].seriesName + '：' + val[i].value + ' kWh' +
                    '<br/>'
                  totle = totle + val[i].value
                }
                returnStr = returnStr +
                  '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:#D6E0FF\'></span>合计：' + totle + ' kWh' +
                  '<br/>'
                returnStr = returnStr + '</div>'
                return returnStr
              }
            }
          },
          yearOption: {
            legend: {
              top: 10,
              right: 35,
              itemGap: 38,
              itemWidth: 10,
              itemHeight: 10,
              data: []
            },
            xAxis: {
              type: 'category',
              data: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              },
              formatter: function (val, n) {
                var returnStr = '<div style=\'text-align:left;\'>' +
                  '时间：' + val[0].name + '<br/>'
                for (var i in val) {
                  returnStr = returnStr +
                    '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + val[i].color + '\'></span>' +
                    val[i].seriesName + '：' + val[i].value + ' kWh' +
                    '<br/>'
                }
                returnStr = returnStr + '</div>'
                return returnStr
              }
            }
          }
        },
        optionfad: {
          grid: {
            x:50,
            y:65,
            x2:55,
            y2:25,
          },
          title: {
            text: '费用及单价',
            show: true,
            top: 5,
            borderColor: '#D6E0FF',
            textStyle: {
              fontSize: '14'
            }
          },
          color: ['#67B4F4', '#FE8252'],
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function (val, n) {
              var returnStr = '<div style=\'text-align:left;\'>' +
                '时间：' + val[0].name + '<br/>'
              for (var i in val) {
                returnStr = returnStr +
                  '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + val[i].color + '\'></span>' +
                  val[i].seriesName + '：' + val[i].value + (val[i].seriesName === '纯电量费用' ? ' 元' : ' 元/kWh') +
                  '<br/>'
              }
              returnStr = returnStr + '</div>'
              return returnStr
            }
          },
          legend: {
            x: 'right',
            padding: [13, 130, ,],
            itemGap: 20,
            itemWidth: 10,
            itemHeight: 10,
            data: [{
              name: '纯电量费用',
              icon: 'circle'
            }, {
              name: '纯电量单价',
              icon: 'circle'
            }],
          },
          xAxis: {
            type: 'category',
            boundaryGap: true,
            data: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31']
          },
          yAxis: [
            {
              type: 'value',
              scale: true,
              name: '单位：元',
              splitNumber: 6,
              min:0,
              boundaryGap: [0.2, 0.2],
              axisLabel: {
                formatter: function (a) {
                  return a >= 1000
                    ? echarts.format.addCommas(a / 1000) + 'k'
                    : a
                }
              }
            },
            {
              type: 'value',
              scale: true,
              offset: -10,
              name: '单位 元/kWh',
              splitNumber: 6,
              splitLine: {
                show: false
              },
              boundaryGap: [0.2, 0.2]
            }
          ],
          series: [{
              name: '纯电量费用',
              type: 'bar',
              barGap: '50%',
              barWidth: '50%',
              barCategoryGap: '70%',
              itemStyle: {
                //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
                emphasis: {
                  barBorderRadius: 50,
                  shadowBlur: 50,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(3,213,151, 0.5)'
                },
                normal: {
                  //柱形图圆角，初始化效果
                  barBorderRadius: 4
                }
              },
              data: []
            },
            {
              name: '纯电量单价',
              type: 'line',
              yAxisIndex: 1,
              data: []
            }
          ]
        },
      }
    },
    methods: {
      selectRent(row) {
        this.currentRentInfo = row;
        this.getDataList();
      },

      // // 获取数据列表
      // getBuildDataList(){
      //    this.$api.okhttp({
      //     url: this.$http.adornUrl("/ecs/ecsbuildinginfo/getDeviceTree"),
      //     method: "get",
      //     params: this.$http.adornParams({
      //       'projectId': this.$util.cookies.get("cuuren_projectId"),
      //       "customerId":this.$util.cookies.get('customer_id'),
      //       "meterType": this.$meterType.ELECTRIC
      //     })
      //   }).then(res=>{
      //     if (res && res.data.code == 0) {
      //       if(res.data.data&&res.data.data.length>0){
      //         let isExt = false;
      //         res.data.data.forEach((ele,index)=>{
      //           if(ele.type=='b'){
      //             ele.disabled=true;
      //           }else{
      //             if(!isExt){
      //               this.currentBuildNode = ele;
      //               isExt = true;
      //             }
      //           }
      //         })
      //       }
      //
      //       this.oralebuildDataList =  res.data.data
      //       this.buildDataList = Util.treeDataTranslate(res.data.data,"id","pid");
      //       this.$nextTick(()=>{
      //          this.$refs.buildTree.setCurrentKey(this.currentBuildNode.id);
      //          this.getDataList();
      //       })
      //     } else{
      //       this.buildDataList = [];
      //     }
      //   })
      // },
      selectBuild (data, checked, indeterminate) {
        if(checked){
          this.$refs.buildTree.setCheckedNodes([]);
          this.currentBuildNode = data;
          this.$refs.buildTree.setChecked(data.id,checked);
          //查询设备列表
          this.getDataList();
        }
      },
      getDataList(){
        this.dataListLoading1 = true
        if(!this.currentRentInfo||this.currentRentInfo.subscriberId==''){
          return;
        }
        // let parentNodeName = this.oralebuildDataList.find(item =>item.id==this.currentBuildNode.pid).name
        // this.currentBuildNode.parentName = parentNodeName
        this.dayDataList = []
        this.monthDataList= []
        this.monthheader =[]
        this.yearDataList= []
        this.yearheader =[]
        var para = {
          // meterCode: '320100A2221101',
          // date:'2020-05',
          // dateType:'2',
          date:Util.dateFormat(Config.searchDate.find(ele=>ele.typeDesc==this.dataForm.dateTypeDesc).formatStr,this.dataForm.date),
          dateType:this.dataForm.dateTypeDesc,
          subscriberId:this.currentRentInfo.subscriberId+'',
          customerId: this.$util.cookies.get("customer_id")
        }
        this.$api.okhttp({
          url: this.$http.adornUrl('/ecm/report/topandlow'),
          method: 'post',
          data: this.$http.adornParams(para)
        }).then(data1=>{
          if(data1.data.code==0){
            if(this.dataForm.dateTypeDesc==1){//日
              let data = data1.data.data
              for (var i = 0; i < data.length; i++) {
                let detail = data[i].detail
                for (var j = 0; j < detail.length; j++) {
                  this.dayDataList.push(
                    {"ObjName": data[i].buildingName, "meterName": data[i].meterCode, "time":detail[j].time, "type": data[i].priceName, "val": detail[j].val, "fee":
                      detail[j].fee}
                  )
                }
              }
            }else if(this.dataForm.dateTypeDesc==2){//月
              this.monthheader = data1.data.header
              this.monthDataList = data1.data.table

            }else{ //年
              this.yearheader = data1.data.header
              this.yearDataList = data1.data.table
            }
          }
         this.dataListLoading1 = false
        }).catch(()=>{
          this.dataListLoading1 = false
        })


      },

      exoprtData(){
        let header= []
        let props= []
        let fileName=""
        let datalist = []
        fileName=`峰谷电报表`+Util.dateFormat(Config.searchDate.find(ele=>ele.typeDesc==this.dataForm.dateTypeDesc).formatStr,this.dataForm.date);
        if(this.dataForm.dateTypeDesc==1){//日
           header=['区域','计量器具名称','小时','类型','用量(kWh)','金额(元)'];
           props=['ObjName','meterName','time','type','val','fee'];
           datalist = this.dayDataList
          if(datalist.length===0){
            this.$message.error("无数据可导出")
            return false;
          }

        }else if(this.dataForm.dateTypeDesc==2){//月

          header=['区域','计量器具名称','日期'];
          props = ['ObjName', 'meterName', 'time'];

          this.monthheader.forEach(it => {
            header.push(it.name);
          props.push(it.indexName + '_' + it.key);
        })
          header.push('总用量(kWh)', '总金额(元)')
          props.push('totalVal', 'totalFee')

          if (this.monthDataList.length === 0) {
            this.$message.error("无数据可导出")
            return false;
          }

          for (let i = 0; i < this.monthDataList.length; i++) {
            let data = this.monthDataList[i]

            let obj = {
              "ObjName": data.buildingName, "meterName": data.meterCode,
              "time": data.time, "totalVal": data.totalVal, "totalFee": data.totalFee
            }

            for (let j = 0; j < data.value.length; j++) {
              obj[data.value[j].priceName + '_val'] = data.value[j].val
              obj[data.value[j].priceName + '_fee'] = data.value[j].fee
            }

            datalist.push(obj)
          }


        }else{ //年
          header=['区域','计量器具名称','月份'];
          props = ['ObjName', 'meterName', 'time'];

          this.yearheader.forEach(it => {
            header.push(it.name);
          props.push(it.indexName + '_' + it.key);
        })
          header.push('总用量(kWh)', '总金额(元)')
          props.push('totalVal', 'totalFee')

          if (this.yearDataList.length === 0) {
            this.$message.error("无数据可导出")
            return false;
          }

          for (let i = 0; i < this.yearDataList.length; i++) {
            let data = this.yearDataList[i]

            let obj = {
              "ObjName": data.buildingName, "meterName": data.meterCode,
              "time": data.time, "totalVal": data.totalVal, "totalFee": data.totalFee
            }

            for (let j = 0; j < data.value.length; j++) {
              obj[data.value[j].priceName + '_val'] = data.value[j].val
              obj[data.value[j].priceName + '_fee'] = data.value[j].fee
            }

            datalist.push(obj)
          }
        }

        this.export2Excel(header,props,fileName,datalist)
      },
      export2Excel (tH, fi, fiNa, dataList) {
        var tHeader = tH
        var filterVal = fi
        var fileName = fiNa
        require.ensure([], () => {
          const {export_json_to_excel} = require('@/utils/Export2Excel.js')
          const list = JSON.parse(JSON.stringify(dataList));
        // let sumVal = list.reduce(function (total, currentValue, currentIndex, arr) {
        //   return total + currentValue.val;
        // }, 0);
        // let sumfee = list.reduce(function (total, currentValue, currentIndex, arr) {
        //   return total + currentValue.fee;
        // }, 0);
        // list.push({
        //   "ObjName":'合计',
        //   "val":sumVal,
        //   "fee":sumfee
        // })

        const data = this.formatJson(filterVal, list)
        export_json_to_excel(tHeader, data, fileName)
      })
      },

      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },
      //日报
      initDayChart (data) {
        let totalUsePower=0;
        let totalFee=0;
        this.option.series[0].data = [];
        this.option.series[0].name = '日电量';
        this.optiondf.series[0].data = [];
        this.optiondf.series[0].name = '日电费';
        //柱状图
        let dayBarOption = Object.assign(this.powerEchart.option,this.powerEchart.dateOption);
        dayBarOption.series =[];
        for (var i = 0; i < data.length; i++) {
          //电量
          totalUsePower= totalUsePower+data[i].tval;
          this.option.series[0].data.push({
            name : data[i].priceName+"电量 : "+data[i].tval+"kWh",
            value : data[i].tval,
            icon : 'circle',
          })
          //费用
          totalFee = totalFee+ data[i].tfee;
          this.optiondf.series[0].data.push({
            name : data[i].priceName+"费用 : "+data[i].tfee+"元",
            value : data[i].tfee,
            icon : 'circle',
          })
          //柱状图
          dayBarOption.legend.data.push({
            icon : 'circle',
            name:data[i].priceName+'用电量',
          })
          let series ={
            name: data[i].priceName+'用电量',
            type: 'bar',
            stack: '用电',
            data:[],
            itemStyle: {
              //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
              emphasis: {
                barBorderRadius: 50,
                shadowBlur: 50,
                shadowOffsetX: 0,
                shadowColor: 'rgba(3,213,151, 0.5)'
              },
            }
          };
          if(i==data.length-1){
            series.itemStyle.normal={
              //柱形图圆角，初始化效果
              barBorderRadius: [58, 58, 0, 0]
            }
          }
          dayBarOption.xAxis.data.forEach(element=>{
            let userTotal=0;
            if(data[i].detail&&data[i].detail.length>0){
              for(let n=0;n<data[i].detail.length;n++){
                if(element==data[i].detail[n].time){
                  userTotal = data[i].detail[n].val
                }
              }
            }
            series.data.push(userTotal);
          })
          dayBarOption.series.push(series);
        }
        //用电量画图
        this.option.series[0].data.unshift({
            name : "总用电量 : "+totalUsePower+"kWh",
            value : 0,
            icon : 'circle',
        });
        this.option.title.text = '总用电量 : ' + totalUsePower + ' kWh';
        this.option.legend.data =this.option.series[0].data;

        //费用画图
        this.optiondf.series[0].data.unshift({
            name : "总用电费用 : "+totalFee+"元",
            value : 0,
            icon : 'circle',
        });
        this.optiondf.title.text = '总用电费用 : ' + totalFee + ' 元'
        this.optiondf.legend.data = this.optiondf.series[0].data;

        //生成日用电量趋势柱状图
        //柱状图
        dayBarOption.title.text ="日用电量趋势";


        this.$nextTick(()=>{
            let myChart = echarts.init(document.getElementById('pie'));//用电量饼图
            myChart.clear();
            myChart.setOption(this.option);
            let myChart1 = echarts.init(document.getElementById('pie1'));//用电量费用
            myChart1.clear();
            myChart1.setOption(this.optiondf);
            let myChart2 = echarts.init(document.getElementById('daystatEchart'));//各个用电量
            myChart2.clear()
            myChart2.setOption(dayBarOption);
        })
      },
      //月报
      initMonthChart (data) {
        let that = this;
        let totalUsePower=0;
        let totalFee=0;
        this.option.series[0].data = [];
        this.option.series[0].name = '月用电量';
        this.optiondf.series[0].data = [];
        this.optiondf.series[0].name = '月用电费';
        //柱状图
        let monthyBarOption = Object.assign(this.powerEchart.option,this.powerEchart.monthOption);
        monthyBarOption.series= [];
        monthyBarOption.tooltip = {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (val, n) {
            return that.monthTimefun(val)
          }
        }
        //费用图
        var optionsfand = {};
        Object.assign(optionsfand, this.optionfad);
        optionsfand.series[0].data=[];
        optionsfand.series[1].data=[];
        optionsfand.xAxis.data = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'];

        optionsfand.tooltip ={
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (val, n) {
            return that.monthTimeFeefun(val)
          }
        }
        for (var i = 0; i < data.length; i++) {
          //电量
          totalUsePower= totalUsePower+data[i].tval;
          this.option.series[0].data.push({
            name : data[i].priceName+"用电量 : "+data[i].tval+"kWh",
            value : data[i].tval,
            icon : 'circle',
          })
          //费用
          totalFee = totalFee+ data[i].tfee;
          this.optiondf.series[0].data.push({
            name : data[i].priceName+"费用 : "+data[i].tfee+"元",
            value : data[i].tfee,
            icon : 'circle',
          })
          //柱状图
          monthyBarOption.legend.data.push({
            icon : 'circle',
            name:data[i].priceName+'用电量',
          })
          let series ={
            name: data[i].priceName+'用电量',
            type: 'bar',
            stack: '用电',
            data:[],
            itemStyle: {
              //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
              emphasis: {
                barBorderRadius: 50,
                shadowBlur: 50,
                shadowOffsetX: 0,
                shadowColor: 'rgba(3,213,151, 0.5)'
              },
            }
          };
          if(i==data.length-1){
            series.itemStyle.normal={
              //柱形图圆角，初始化效果
              barBorderRadius: [58, 58, 0, 0]
            }
          }
          monthyBarOption.xAxis.data.forEach(element=>{
            let userTotal=0;
            if(data[i].detail&&data[i].detail.length>0){
              for(let n=0;n<data[i].detail.length;n++){
                if(element==data[i].detail[n].time){
                  userTotal = data[i].detail[n].val;
                }
              }
            }
            series.data.push(userTotal);
          })
          monthyBarOption.series.push(series);
        }
        optionsfand.xAxis.data.forEach(element=>{
          let userFee = 0;
          let userPrice = 0;
          for (var i = 0; i < data.length; i++) {
            if(data[i].detail&&data[i].detail.length>0){
              for(let n=0;n<data[i].detail.length;n++){
                if(element==data[i].detail[n].time){
                  userFee =userFee+ data[i].detail[n].fee;
                  userPrice =userPrice+ data[i].detail[n].per;
                }
              }
            }
          }
          optionsfand.series[0].data.push(userFee);
          optionsfand.series[1].data.push((userPrice/data.length).toFixed(2));
        }),
        //用电量饼图
        this.option.series[0].data.unshift({
            name : "总用电量 : "+totalUsePower+"kWh",
            value : 0,
            icon : 'circle',
        });
        this.option.title.text = '总用电量 : ' + totalUsePower + ' kWh';
        this.option.legend.data =this.option.series[0].data;
        //费用饼图
        this.optiondf.series[0].data.unshift({
            name : "总用电费用 : "+totalFee+"元",
            value : 0,
            icon : 'circle',
        });
        this.optiondf.title.text = '总用电费用 : ' + totalFee + ' 元'
        this.optiondf.legend.data = this.optiondf.series[0].data;
        //柱状图
        monthyBarOption.title.text ="月用电量趋势";
        this.$nextTick(()=>{
          let myChart = echarts.init(document.getElementById('monthpie'));//用电量饼图
          myChart.clear();
          myChart.setOption(this.option);
          let myChart1 = echarts.init(document.getElementById('monthpie1'));//用电量费用
          myChart1.clear();
          myChart1.setOption(this.optiondf);
          let myChart2 = echarts.init(document.getElementById('monthstatEchart'));//各个用电量
          myChart2.clear()
          myChart2.setOption(monthyBarOption);
          let myChart3 = echarts.init(document.getElementById('monthfeestatEchart'));//各个用电量
          myChart3.clear()
          myChart3.setOption(optionsfand);
        })
      },
      // 年报
      initYearChart (data) {
        let that = this;
        let totalUsePower=0;
        let totalFee=0;
        this.option.series[0].data = [];
        this.option.series[0].name = '年用电量';
        this.optiondf.series[0].data = [];
        this.optiondf.series[0].name = '年用电费';
        //柱状图
        let yearBarOption = Object.assign(this.powerEchart.option,this.powerEchart.yearOption);
        yearBarOption.series= [];
        yearBarOption.tooltip = {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (val, n) {
            return that.yearTimefun(val)
          }
        }
        //费用图
        var optionsfand = {};
        Object.assign(optionsfand, this.optionfad);
        optionsfand.series[0].data=[];
        optionsfand.series[1].data=[];
        optionsfand.xAxis.data = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
        optionsfand.tooltip ={
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (val, n) {
            return that.yearTimeFeefun(val)
          }
        }
        for (var i = 0; i < data.length; i++) {
          //电量
          totalUsePower= totalUsePower+data[i].tval;
          this.option.series[0].data.push({
            name : data[i].priceName+"用电量 : "+data[i].tval+"kWh",
            value : data[i].tval,
            icon : 'circle',
          })
          //费用
          totalFee = totalFee+ data[i].tfee;
          this.optiondf.series[0].data.push({
            name : data[i].priceName+"费用 : "+data[i].tfee+"元",
            value : data[i].tfee,
            icon : 'circle',
          })
          //柱状图
          yearBarOption.legend.data.push({
            icon : 'circle',
            name:data[i].priceName+'用电量',
          })
          let series ={
            name: data[i].priceName+'用电量',
            type: 'bar',
            stack: '用电',
            data:[],
            itemStyle: {
              //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
              emphasis: {
                barBorderRadius: 50,
                shadowBlur: 50,
                shadowOffsetX: 0,
                shadowColor: 'rgba(3,213,151, 0.5)'
              },
            }
          };
          if(i==data.length-1){
            series.itemStyle.normal={
              //柱形图圆角，初始化效果
              barBorderRadius: [58, 58, 0, 0]
            }
          }
          yearBarOption.xAxis.data.forEach(element=>{
            let userTotal=0;
            if(data[i].detail&&data[i].detail.length>0){
              for(let n=0;n<data[i].detail.length;n++){
                if(element==data[i].detail[n].time){
                  userTotal = data[i].detail[n].val
                }
              }
            }
            series.data.push(userTotal);
          })
          yearBarOption.series.push(series);
        }
        //用电量饼图
        this.option.series[0].data.unshift({
            name : "总用电量 : "+totalUsePower+"kWh",
            value : 0,
            icon : 'circle',
        });
        this.option.title.text = '总用电量 : ' + totalUsePower + ' kWh';
        this.option.legend.data =this.option.series[0].data;

        //费用饼图
        this.optiondf.series[0].data.unshift({
            name : "总用电费用 : "+totalFee+"元",
            value : 0,
            icon : 'circle',
        });
        this.optiondf.title.text = '总用电费用 : ' + totalFee + ' 元'
        this.optiondf.legend.data = this.optiondf.series[0].data;

        //柱状图
        yearBarOption.title.text ="年用电量趋势";

        optionsfand.xAxis.data.forEach(element=>{
          let userFee = 0;
          let userPrice = 0;
          for (var i = 0; i < data.length; i++) {
            if(data[i].detail&&data[i].detail.length>0){
              for(let n=0;n<data[i].detail.length;n++){
                if(element==data[i].detail[n].time){
                  userFee =userFee+ data[i].detail[n].fee;
                  userPrice =userPrice+ data[i].detail[n].per;
                }
              }
            }
          }
          optionsfand.series[0].data.push(userFee);
          optionsfand.series[1].data.push((userPrice/data.length).toFixed(2));
        }),
        this.$nextTick(()=>{
          let myChart = echarts.init(document.getElementById('yearpie'));//用电量饼图
          myChart.clear();
          myChart.setOption(this.option);
          let myChart1 = echarts.init(document.getElementById('yearpie1'));//用电量费用
          myChart1.clear();
          myChart1.setOption(this.optiondf);
          let myChart2 = echarts.init(document.getElementById('yearstatEchart'));//各个用电量
          myChart2.clear()
          myChart2.setOption(yearBarOption);
          let myChart3 = echarts.init(document.getElementById('yearfeeEchart'));//各个用电量
          myChart3.clear()
          myChart3.setOption(optionsfand);
        })
      },
      monthTimefun (val) {
        var totle = 0
        var returnStr = '<div style=\'text-align:left;\'>' +
          '时间：' + (new Date(new Date(this.dataForm.date).getFullYear(), new Date(this.dataForm.date).getMonth(), val[0].name).format('yyyy-MM-dd')) + '<br/>'
        for (var i in val) {
          returnStr = returnStr +
            '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + val[i].color + '\'></span>' +
            val[i].seriesName + '：' + val[i].value + ' kWh' +
            '<br/>'
          totle = totle + parseFloat(val[i].value)
        }
        returnStr = returnStr +
          '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:#D6E0FF\'></span>合计：' + totle.toFixed(1) + ' kWh' +
          '<br/>'
        returnStr = returnStr + '</div>'
        return returnStr
      },
      monthTimeFeefun (val) {
        var returnStr = '<div style=\'text-align:left;\'>' +
          '时间：' + (new Date(new Date(this.dataForm.date).getFullYear(), new Date(this.dataForm.date).getMonth(), val[0].name).format('yyyy-MM-dd')) + '<br/>'
        for (var i in val) {
          returnStr = returnStr +
            '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + val[i].color + '\'></span>' +
            val[i].seriesName + '：' + val[i].value + (val[i].seriesName === '纯电量费用' ? ' 元' : ' 元/kWh') +
            '<br/>'
        }
        returnStr = returnStr + '</div>'
        return returnStr
      },
      yearTimefun (val) {
        var totle = 0
        var returnStr = '<div style=\'text-align:left;\'>' +
          '时间：' + (new Date(new Date(this.dataForm.date).getFullYear(), val[0].name - 1, 1).format('yyyy-MM')) + '<br/>'
        for (var i in val) {
          returnStr = returnStr +
            '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + val[i].color + '\'></span>' +
            val[i].seriesName + '：' + val[i].value + ' kWh' +
            '<br/>'
          totle = totle + parseFloat(val[i].value)
        }
        returnStr = returnStr +
          '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:#D6E0FF\'></span>合计：' + totle.toFixed(1) + ' kWh' +
          '<br/>'
        returnStr = returnStr + '</div>'
        return returnStr
      },
      yearTimeFeefun (val) {
        var returnStr = '<div style=\'text-align:left;\'>' +
          '时间：' + (new Date(new Date(this.dataForm.date).getFullYear(), val[0].name - 1, 1).format('yyyy-MM')) + '<br/>'
        for (var i in val) {
          returnStr = returnStr +
            '<span style=\'display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + val[i].color + '\'></span>' +
            val[i].seriesName + '：' + val[i].value + (val[i].seriesName === '纯电量费用' ? ' 元' : ' 元/kWh') +
            '<br/>'
        }
        returnStr = returnStr + '</div>'
        return returnStr
      },
      getRendDataList(){
        this.dataListLoading = true
        this.$api.okhttp({
          url: this.$http.adornUrl('/ecs/ecssubscriberinfo/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': 1,
            'limit': 1000000,
            'paramKey': '',
            "customerId":this.$util.cookies.get('customer_id')
          })
        }).then((data) => {
          if (data && data.code === 0) {
          this.rentOriginList = data.page.list;
          this.rentList = data.page.list;
          if(this.rentList.length>0){
            this.currentRentInfo=this.rentList[0];
            this.$nextTick(()=>{
              this.$refs.rentTable.setCurrentRow(this.currentRentInfo);
            this.getDataList()
          })
          }
        } else {
          this.rentOriginList = []
        }
        this.dataListLoading = false
      })
      },
    },
    mounted () {
    //  this.getBuildDataList();
      this.getRendDataList();
    },
    computed: {
      containerHeight() {
        return Util.getClientHeight() - 143+this.chartHeight/2;
      },
      chartHeight(){
        return Util.getClientHeight() - 223;
      }
    },
    watch: {
      'dataForm.dateTypeDesc':function(nvalue, pvalue){
        this.dataForm.dateType = this.Config.searchDate.find(ele=>ele.typeDesc==this.dataForm.dateTypeDesc).date;
      },

      searchKey(newVal,oldVal){
        if(this.searchKey&&this.searchKey!=''){
          this.rentList= this.rentOriginList.filter(ele=>ele.subscriberName.indexOf(this.searchKey)>=0||ele.phone.indexOf(this.searchKey)>=0);
        }
        else{
          this.rentList = this.rentOriginList;
        }
    },
    }
  }
</script>

<style scoped lang="scss">
  @import "../../assets/scss/_variables";

  $light-green: lightgray;
  $active-color: lightgreen;
  .el-form-item{
    margin-bottom: 0px;
  }
  .bg-white{
    background: white;
    box-shadow: 0px 0px 2px 2px #f7f6f6;
    padding: 10px;
  }
  .device-area1 {
    // box-shadow: 0px 0px 2px 2px #f7f6f6;
    border: solid 1px #808080;
    padding-top: 10px;
    padding-left: 10px;
    overflow: auto;
  }
  .search-area{
    display:flow-root;
    margin-bottom: 10px;
    border: 1px solid #808080;
    border-left: none;
    border-right: none;
    padding: 10px 0px 10px 0px;
  }
  .edit-box {
    width: 100%;
    height: 100%;
    padding: 0;
  }

  .add-top {
    width: 100%;
    height: 50px;
    border-top-left-radius: 5px;
    background: $color-add;
    display: flex;
    text-indent: $content-padding-15;
    align-items: center;
    color: #fff;
  }

  .add-title {
    width: 80%;
    margin-left: 10%;
  }

  .step-box {
    display: flex;
    margin-top: 20px;
    height: 40px;
    box-sizing: border-box;
    color: #fff;
  }

  .monitor-tree-d {
    position: absolute;
    height: 100%;
    top: 0;
    right: 0;
  }

  .chartbox {
    display: block;
    width: 100%;
    clear: both;
    content: "";
    overflow: hidden;
  }

  .step-sub {
    display: inline-block;
    box-sizing: border-box;
    width: 100%;
    font-size: 10px;
    padding-top: 15px;
    padding-left: 20px;
    padding-bottom: 5px;
    padding-right: 20px;
  }

  .step-line {
    display: inline-block;
    width: 100%;
    height: 1px;
    background-color: $font-color;
  }

  .step-box > span {
    flex: 1;
    height: 40px;
    margin: 0 15px;
    padding: 0 10px;
    display: flex;
    align-items: center;
    background-color: $light-green;
    position: relative;
  }

  .step-box > span.active {
    background-color: $active-color;
  }

  .step-box > span:not(:first-child):before {
    content: '';
    position: absolute;
    top: 0;
    left: -15px;
    bottom: 0;
    border-top: 20px solid $light-green;
    border-left: 15px solid transparent;
    border-bottom: 20px solid $light-green;
  }

  .step-box > span.active:not(:first-child):before {
    content: '';
    position: absolute;
    top: 0;
    left: -15px;
    bottom: 0;
    border-top: 20px solid $active-color;
    border-left: 15px solid transparent;
    border-bottom: 20px solid $active-color;
  }

  .step-box > span:after {
    content: '';
    position: absolute;
    top: 0;
    right: -15px;
    bottom: 0;
    border-top: 20px solid transparent;
    border-left: 15px solid $light-green;
    border-bottom: 20px solid transparent;
  }

  .step-box > span.active:after {
    content: '';
    position: absolute;
    top: 0;
    right: -15px;
    bottom: 0;
    border-top: 20px solid transparent;
    border-left: 15px solid $active-color;
    border-bottom: 20px solid transparent;
  }

  .seq {
    font-size: 35px;
    font-weight: 900;
    margin-right: 15px;
  }

  .icon-size {
    font-size: 25px;
    font-weight: 900;
    margin-right: 15px;
  }

  .step-word {
    font-size: 15px;
    font-weight: 900;
  }

  .el-button {
    margin: 0;
  }

  .el-button--success {
    margin-left: 5px;
  }

  .power-statistics {
    /*padding: 5px 15px 10px;*/
    height: 310px;
    background: $font-white;
  }
  .power-statistics-one {
    /*padding: 5px 15px 10px;*/
    background: $font-white;
  }
  .statistics-d-one > div {
    width: 100%;
  }
  .statistics-d > div {
    width: 100%;
  }

  .note {
    padding: 20px;
    text-align: center;
    color: #666;
  }

  .note img {
    width: 140px;
  }

  .clearfloat:after {
    display: block;
    clear: both;
    content: "";
    visibility: hidden;
    height: 0
  }

  .clearfloat {
    overflow:hidden;
    zoom: 1
  }

  .label_time {
    font-family: MicrosoftYaHei;
    display: -moz-inline-block;
    display: inline-block;
    cursor: pointer;
    line-height: 36px;
    background-color: #F8F8F8;
    padding: 2px 0 0 0px;
    border: 1px solid #DDDEE1;
    font-size: 14px;
    text-align: center;
    color: #999999;
    width: 110px;
  }

  div.checked {
    /*border: 1px solid #678AF4;*/
    background-color: #678AF4;
    color: #FFFFFF;
  }

  .bottomSty {
    border-bottom: 1px solid #678AF4;
  }

</style>
